package com.buanalintas.sandals.pos.saleshopdetail;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.entities.MasterUnit;
import com.buanalintas.bynga.formatter.MoneyFormatter;
import com.buanalintas.bynga.generator.PageTransactionDetailList;
import com.buanalintas.sandals.pos.entities.PosMasterItem;
import com.buanalintas.sandals.pos.entities.PosMasterItemStock;
import com.buanalintas.sandals.pos.entities.PosMasterSize;
import com.buanalintas.sandals.pos.entities.PosMasterStatus;
import com.buanalintas.sandals.pos.entities.PosTransactionSaleShopDetail;
import com.buanalintas.sandals.pos.item.Item;
import com.buanalintas.sandals.pos.status.Status;
import com.buanalintas.sandals.pos.saleshopdetail.AddSize;
import java.math.BigDecimal;
import java.util.List;
import java.util.logging.Level;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpSession;

public class SaleShopDetail extends Page {

    private Field saleShopDetailId;
    private Field saleShopDetailSaleShopId;
    private Field saleShopDetailItemId;
    private Field saleShopDetailSizeId;
    private Field saleShopDetailSize;
    private Field saleShopDetailQuantity;
    private Field saleShopDetailPrice;
    private Field saleShopDetailDiscountPercent;
    private Field saleShopDetailDiscountNominal;
    private Field saleShopDetailTotal;
    private  boolean ada = true;

    public SaleShopDetail() {
        super();
        setTheClass(PosTransactionSaleShopDetail.class);

        saleShopDetailId = new Field();
        saleShopDetailId.setName("saleShopDetailId");
        saleShopDetailId.setCaption("id");
        saleShopDetailId.setListProperties("");
        saleShopDetailId.setInputProperties("");
        getFields().add(saleShopDetailId);

        saleShopDetailSaleShopId = new Field();
        saleShopDetailSaleShopId.setName("saleShopDetailSaleShopId");
        saleShopDetailSaleShopId.setCaption("sale id");
        saleShopDetailSaleShopId.setListProperties("");
        saleShopDetailSaleShopId.setInputProperties("");
        getFields().add(saleShopDetailSaleShopId);

        saleShopDetailItemId = new Field();
        saleShopDetailItemId.setName("saleShopDetailItemId");
        saleShopDetailItemId.setCaption("item");
        saleShopDetailItemId.setListProperties("");
        saleShopDetailItemId.setInputProperties(" size=\"30\"");
        saleShopDetailItemId.getSelectorAction().add(new String[]{"value", "saleShopDetailPrice", "itemPriceShop"});
        saleShopDetailItemId.getSelectorColumns().add(new String[]{"itemCode", " Code", "width=\"5%\" nowrap"});
        saleShopDetailItemId.getSelectorColumns().add(new String[]{"itemModel", " Model", "width=\"90%\""});
        saleShopDetailItemId.setSelectorOrder("t.itemCode");
        saleShopDetailItemId.setRequired(true);
        getFields().add(saleShopDetailItemId);
        
        saleShopDetailSize = new Field();
        saleShopDetailSize.setName("saleShopDetailSize");
        saleShopDetailSize.setCaption("size");
        saleShopDetailSize.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        saleShopDetailSize.setEntityRelation(PosMasterSize.class);
        saleShopDetailSize.setInputType(Field.INPUT_CHECK_BOX);
        saleShopDetailSize.setRequired(true);
        getFields().add(saleShopDetailSize);

        saleShopDetailSizeId = new Field();
        saleShopDetailSizeId.setName("saleShopDetailSizeId");
        saleShopDetailSizeId.setCaption("size");
        saleShopDetailSizeId.setListProperties(" align=\"left\" width=\"30%\" nowrap");
        saleShopDetailSizeId.setEntityRelation(PosMasterSize.class);
        saleShopDetailSizeId.setRequired(true);
        getFields().add(saleShopDetailSizeId);

        saleShopDetailQuantity = new Field();
        saleShopDetailQuantity.setName("saleShopDetailQuantity");
        saleShopDetailQuantity.setCaption("quantity");
        saleShopDetailQuantity.setListProperties(" align=\"right\" width=\"5%\" nowrap");
        saleShopDetailQuantity.setInputProperties(" size=\"3\"");
        saleShopDetailQuantity.setRequired(true);
        getFields().add(saleShopDetailQuantity);

        saleShopDetailPrice = new Field();
        saleShopDetailPrice.setName("saleShopDetailPrice");
        saleShopDetailPrice.setCaption("price");
        saleShopDetailPrice.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleShopDetailPrice.setInputProperties(" size=\"8\"");
        saleShopDetailPrice.setRequired(true);
        saleShopDetailPrice.setFormater(MoneyFormatter.getInstance());
        getFields().add(saleShopDetailPrice);

        saleShopDetailDiscountPercent = new Field();
        saleShopDetailDiscountPercent.setName("saleShopDetailDiscountPercent");
        saleShopDetailDiscountPercent.setCaption("discount percent");
        saleShopDetailDiscountPercent.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleShopDetailDiscountPercent.setInputProperties(" size=\"8\"");
        getFields().add(saleShopDetailDiscountPercent);

        saleShopDetailDiscountNominal = new Field();
        saleShopDetailDiscountNominal.setName("saleShopDetailDiscountNominal");
        saleShopDetailDiscountNominal.setCaption("discount nominal");
        saleShopDetailDiscountNominal.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleShopDetailDiscountNominal.setInputProperties(" size=\"8\"");
        saleShopDetailDiscountNominal.setFormater(MoneyFormatter.getInstance());
        getFields().add(saleShopDetailDiscountNominal);

        saleShopDetailTotal = new Field();
        saleShopDetailTotal.setName("saleShopDetailTotal");
        saleShopDetailTotal.setCaption("total");
        saleShopDetailTotal.setListProperties(" align=\"right\" width=\"10%\" nowrap");
        saleShopDetailTotal.setInputProperties(" size=\"8\"");
        saleShopDetailTotal.setFormater(MoneyFormatter.getInstance());
        getFields().add(saleShopDetailTotal);

        getActions().add(Action.TRANS_DETAIL_LIST);
        getActions().add(Action.TRANS_DETAIL_ADD);
        getActions().add(Action.TRANS_DETAIL_EDIT);

        getFieldsAdd().clear();
        getFieldsAdd().add(saleShopDetailItemId);
        getFieldsAdd().add(saleShopDetailSize);
        getFieldsAdd().add(saleShopDetailQuantity);
        getFieldsAdd().add(saleShopDetailPrice);
        getFieldsAdd().add(saleShopDetailDiscountPercent);
        getFieldsAdd().add(saleShopDetailDiscountNominal);

        getFieldsEdit().clear();
        getFieldsEdit().add(saleShopDetailItemId);
        getFieldsEdit().add(saleShopDetailSizeId);
        getFieldsEdit().add(saleShopDetailQuantity);
        getFieldsEdit().add(saleShopDetailPrice);
        getFieldsEdit().add(saleShopDetailDiscountPercent);
        getFieldsEdit().add(saleShopDetailDiscountNominal);

        getFieldsList().clear();
        getFieldsList().add(saleShopDetailItemId);
        getFieldsList().add(saleShopDetailSizeId);
        getFieldsList().add(saleShopDetailQuantity);
        getFieldsList().add(saleShopDetailPrice);
        getFieldsList().add(saleShopDetailDiscountPercent);
        getFieldsList().add(saleShopDetailDiscountNominal);
        getFieldsList().add(saleShopDetailTotal);

        setController(new SaleShopDetailController(this));
    }

    @Override
    public StringBuffer process() {
        if (getAction().equals(Action.TRANS_DETAIL_ADD)) {
            return AddSize.process(this);
        }
        if (getAction().equals(Action.TRANS_DETAIL_LIST)) {
            Template template = new Template();
            template.loadTemplate("/com/buanalintas/sandals/pos/saledetail/trans-list.html");
            return PageTransactionDetailList.process(this, template);
        }
        return super.process();
    }
    
    @Override
    public String validate(Object data) {
        EntityManager em = getEntityManager();
        PosMasterStatus statusGood = Status.getStatusGood(em);
        System.out.println(statusGood.getStatusName());
        PosTransactionSaleShopDetail saleShopDetail = (PosTransactionSaleShopDetail) data;
        PosMasterItemStock stock = Item.getStock(em, saleShopDetail.getSaleShopDetailItemId(), getCurrentUnit(), statusGood, saleShopDetail.getSaleShopDetailItemId().getItemColorId(), saleShopDetail.getSaleShopDetailSizeId());
        if (saleShopDetail.getSaleShopDetailQuantity().compareTo(stock.getItemStockValue()) > 0) {
            return saleShopDetail.getSaleShopDetailItemId() + " " + Dictionary.getValue(this, "insufficient stock") + ", " + Dictionary.getValue(this, "current stock: ") + ": " + stock.getItemStockValue() + " " + Dictionary.getValue(this, "will be sale") + ": " + saleShopDetail.getSaleShopDetailQuantity();
        }
        return null;
    }


    @Override
    public String doAction() {
        String barcode = Utility.getPostParameterEmpty(this, "barcode");
        int i = 0;
        if (!"".equals(barcode)) {
            HttpSession session = getRequest().getSession();
            try {
                System.out.println(" loop");
                EntityManager em = getEntityManager();
                PosMasterItem item = (PosMasterItem) em.createQuery("SELECT t FROM PosMasterItem t WHERE t.itemBarcode='" + barcode + "'").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                List<PosTransactionSaleShopDetail> list = ((List) session.getAttribute("transactions"));

                boolean exists = false;

                System.out.println("========>>>1");

                if (ada) {
                    for (PosTransactionSaleShopDetail sd : list) {
                        if (sd.getSaleShopDetailItemId().equals(item)) {
                            exists = true;
                            sd.setSaleShopDetailQuantity(sd.getSaleShopDetailQuantity() + 1);
                            sd.setSaleShopDetailTotal(sd.getSaleShopDetailTotal().add(sd.getSaleShopDetailPrice()));

                            ada = false;
                            break;

                        } else {
                            ada = true;
                            exists = false;
                        }
                    }
                }

                System.out.println("========>>>2");
                if (!exists) {
                    if (ada) {
                        PosTransactionSaleShopDetail detail = new PosTransactionSaleShopDetail();
                        System.out.println(item.getItemModel() + " kok jalan "
                                + detail.getSaleShopDetailQuantity());
                        detail.setSaleShopDetailItemId(item);
                            detail.setSaleShopDetailQuantity(1);

                        detail.setSaleShopDetailPrice(item.getItemPriceBasic());

                        detail.setSaleShopDetailDiscountNominal(BigDecimal.ZERO);
                        detail.setSaleShopDetailDiscountPercent(BigDecimal.ZERO);

                        detail.setSaleShopDetailTotal(item.getItemPriceBasic());
                        list.add(detail);
                    }
                    ada = true;
                    exists = false;
                }

            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
        }
        return super.doAction();
    }

    class SaleShopDetailController extends Controller {

        public SaleShopDetailController(Page page) {
            super(page);
        }

        @Override
        public void beforeInsertDetail(Object data) {
            HttpSession session = getRequest().getSession();
            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            System.out.println(statusGood.getStatusName());
            PosTransactionSaleShopDetail saleShopDetail = (PosTransactionSaleShopDetail) data;
            PosMasterItemStock stock = Item.getStock(em, saleShopDetail.getSaleShopDetailItemId(), (MasterUnit) session.getAttribute("bynga.unit"), statusGood, saleShopDetail.getSaleShopDetailItemId().getItemColorId(), saleShopDetail.getSaleShopDetailSizeId());
            if (saleShopDetail.getSaleShopDetailQuantity().compareTo(stock.getItemStockValue()) > 0) {
                try {
                    System.out.println("Stok Detail Quantity" + stock.getItemStockValue());
                } catch (Exception ex) {
                    java.util.logging.Logger.getLogger(SaleShopDetail.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            BigDecimal total = BigDecimal.ZERO;
            BigDecimal quantity = new BigDecimal(saleShopDetail.getSaleShopDetailQuantity());
            total = saleShopDetail.getSaleShopDetailPrice().multiply(quantity);
            BigDecimal percent = BigDecimal.ZERO;
            try {
                percent = total.multiply(saleShopDetail.getSaleShopDetailDiscountPercent().divide(new BigDecimal(100)));
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            total = total.subtract(percent);
            try {
                total = total.subtract(saleShopDetail.getSaleShopDetailDiscountNominal());
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            saleShopDetail.setSaleShopDetailTotal(total);
        }
    }
}
